import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { addCartList, deleteCart, getCartList } from '@/api/cart.js'
import { useUserStore } from '@/stores/modules/user.js'

export const useCartStore = defineStore(
  'cart',
  () => {
    const cartList = ref([])
    const userStore = useUserStore()
    const isLogin = computed(() => {
      return userStore.token
    })
    // 刷新购物车
    const refreshCart = async () => {
      const res = await getCartList()
      cartList.value = res.result
    }
    // 计算购物车总数量
    const cartCount = computed(() => {
      return cartList.value.reduce((total, item) => total + item.count, 0)
    })
    const cartItemCount = computed(() => {
      return cartList.value.length
    })
    // 计算购物车总价格
    const cartTotal = computed(() => {
      const selectedItems = cartList.value.filter((item) => item.selected)
      return selectedItems.reduce((total, item) => total + item.count * item.price, 0)
    })
    const cartSelectedCount = computed(() => {
      return cartList.value.reduce((total, item) => {
        return item.selected ? total + item.count : total
      }, 0)
    })
    const isAllSelected = computed(() => {
      return cartList.value.length > 0 && cartList.value.every((item) => item.selected)
    })
    const addCartItem = async (item) => {
      if (isLogin.value) {
        const { skuId, count } = item
        const addRes = await addCartList({ skuId, count })
        console.log(addRes)
        await refreshCart()
      } else {
        const existingItem = cartList.value.find((cartItem) => item.id === cartItem.id)
        if (existingItem) {
          // 如果商品已存在，增加数量
          existingItem.count += item.count
        } else {
          // 如果商品不存在，添加新商品
          cartList.value.push(item)
        }
      }
    }
    const changeSelected = (id, selected) => {
      const item = cartList.value.find((item) => item.id === id)
      if (item) {
        item.selected = selected
      }
    }
    // 删除购物车商品
    const removeCartItem = async (skuIds) => {
      if (isLogin.value) {
        const res = await deleteCart([skuIds])
        console.log('删除', res)
        await refreshCart()
      } else {
        const index = cartList.value.findIndex((item) => item.id === id)
        if (index > -1) {
          cartList.value.splice(index, 1)
        }
      }
    }

    // 更新商品数量
    const updateCartItemCount = (id, count) => {
      const item = cartList.value.find((item) => item.id === id)
      if (item) {
        item.count = count
      }
    }

    // 清空购物车
    const clearCart = () => {
      cartList.value = []
    }

    return {
      cartList,
      cartCount,
      cartTotal,
      addCartItem,
      removeCartItem,
      updateCartItemCount,
      clearCart,
      cartItemCount,
      cartSelectedCount,
      changeSelected,
      isAllSelected,
      refreshCart,
    }
  },
  {
    persist: true,
  },
)
